package com.example.tourstor;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;

public class TravelCostActivity extends AppCompatActivity {
    private EditText Ttime,Tcost;
    private TextView wmt,payway,predict,title,Wmoney,Mmoney,predictW,predictM,W,M;
    private Button minus,plus,title_btn_left,title_btn_right;
    private View week,month,Wmt;

    private int ttime=12,tcost;
    private float wmoney,mmoney,predictw,predictm;
    private Calendar calender;
    private String TAG="TravelCostActivity";
    private String click="2";
    private Thread thread;
    private java.sql.Date date1,smdate;
    private String wtime,mtime,date;
    private long between_days;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_travel_cost);
        setTitle();
        init();

        final SharedPreferences sharedPreferences=getSharedPreferences("Tstart", Activity.MODE_PRIVATE);
        date=sharedPreferences.getString("Tstart",null);
        Log.i(TAG, "onCreate: 选择的时间是："+date);

        if(date!=null){
            java.util.Date date2=calender.getTime();
            smdate=new java.sql.Date(date2.getTime());

            date1= java.sql.Date.valueOf(date);
            Calendar cal = Calendar.getInstance();
            cal.setTime(smdate);
            long time1 = cal.getTimeInMillis();
            cal.setTime(date1);
            long time2 = cal.getTimeInMillis();
            between_days=((time2-time1)/(1000*3600*24))/30;
            Log.i(TAG, "onCreate: between_days: "+between_days);

            Ttime.setText(String.valueOf(between_days));
            ttime= Integer.parseInt(Ttime.getText().toString());
            predict.setText("最迟"+date+"达成");
        }


        title_btn_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(tcost==0){
                    Toast.makeText(TravelCostActivity.this, "请输入目标金额", Toast.LENGTH_LONG).show();
                }else if(ttime==0){
                    Toast.makeText(TravelCostActivity.this, "请确定实现时间", Toast.LENGTH_LONG).show();
                }else if(TextUtils.isEmpty(wmt.getText())){
                    Toast.makeText(TravelCostActivity.this, "请确定转入时间", Toast.LENGTH_LONG).show();
                }else {

                    Intent intent =new Intent(TravelCostActivity.this,MakePlanActivity.class);
                    intent.putExtra("Tcost",tcost);
                    intent.putExtra("Ttime",ttime);
                    if(click.equals("0")){
                        intent.putExtra("WMm",wmoney);
                        intent.putExtra("WMt",wtime);

                    }else if(click.equals("1")){
                        intent.putExtra("WMm",mmoney);
                        intent.putExtra("WMt",mtime);
                    }
                    intent.putExtra("click",click);
                    setResult(33, intent);
                    finish();
                }
            }
        });
    }
    public void init(){
        Ttime=findViewById(R.id.Ttime);
        Tcost=findViewById(R.id.Tcost);

        wmt=findViewById(R.id.wmt);
        payway=findViewById(R.id.payway);
        predict=findViewById(R.id.predict);
        Wmoney=findViewById(R.id.Wmoney);
        Mmoney=findViewById(R.id.Mmoney);
        predictW=findViewById(R.id.predictW);
        predictM=findViewById(R.id.predictM);
        W=findViewById(R.id.W);
        M=findViewById(R.id.M);

        minus=findViewById(R.id.minus);
        plus=findViewById(R.id.plus);

        week=findViewById(R.id.week);
        month=findViewById(R.id.month);
        Wmt=findViewById(R.id.Wmt);

        Log.i(TAG, "init: 获取所有控件");


        Ttime();
        Wmt();
        Payway();
    }

    public void Ttime(){
        calender = Calendar.getInstance();
        final int year= Integer.parseInt(String.valueOf(calender.get(Calendar.YEAR)));
        final int nowmonth= Integer.parseInt(String.valueOf(calender.get(Calendar.MONTH)+1));
        final String day= String.valueOf(calender.get(Calendar.DAY_OF_MONTH));

        Log.i(TAG, "Ttime: 日期："+year+"年"+nowmonth+"月"+day+"日");

        Tcost.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()!=0){
                    tcost=Integer.parseInt(String.valueOf(Tcost.getText()));
                    Log.i(TAG, "onCreate: 目标金额为："+tcost);
                    predict();
                }

            }
        });


        Ttime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length()!=0){
                    ttime= Integer.parseInt(String.valueOf(Ttime.getText()));
                    if(ttime<(between_days+1)){
                        if((nowmonth+ttime)<=12){
                            String text=year+"年"+(nowmonth+ttime)+"月"+day+"日预计达成";
                            predict.setText(text);
                        }else{
                            int newyear=year+(nowmonth+ttime)/12;
                            int newmonth=(nowmonth+ttime)%12;
                            String text="";
                            if(newmonth==0){
                                text=newyear+"年"+"12月"+day+"日预计达成";
                            }else {
                                text=newyear+"年"+newmonth+"月"+day+"日预计达成";
                            }
                            predict.setText(text);
                        }
                        predict();
                    }else {
                        Toast.makeText(TravelCostActivity.this,"实现时间不能超过出行时间",Toast.LENGTH_LONG).show();
                    }
                }

            }
        });

        minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ttime= Integer.parseInt(String.valueOf(Ttime.getText()));
                if(ttime>0){
                    ttime=ttime-1;
                    Ttime.setText(String.valueOf(ttime));

                    if((nowmonth+ttime)<=12){
                        String text=year+"年"+(nowmonth+ttime)+"月"+day+"日预计达成";
                        predict.setText(text);
                    }else{

                        int newyear=year+(nowmonth+ttime)/12;
                        int newmonth=(nowmonth+ttime)%12;
                        String text="";
                        if(newmonth==0){
                            text=newyear+"年"+"12月"+day+"日预计达成";
                        }else {
                            text=newyear+"年"+newmonth+"月"+day+"日预计达成";
                        }
                        predict.setText(text);
                    }
                    predict();

                }else {
                    Toast.makeText(TravelCostActivity.this,"实现时间不能小于0",Toast.LENGTH_LONG).show();
                }

            }
        });
        plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ttime= Integer.parseInt(String.valueOf(Ttime.getText()));
                if(ttime<(between_days+1)){
                    ttime=ttime+1;
                    Ttime.setText(String.valueOf(ttime));
                    if((nowmonth+ttime)<=12){
                        String text=year+"年"+(nowmonth+ttime)+"月"+day+"日预计达成";
                        predict.setText(text);
                    }else{
                        int newyear=year+(nowmonth+ttime)/12;
                        int newmonth=(nowmonth+ttime)%12;
                        String text="";
                        if(newmonth==0){
                            text=newyear+"年"+"12月"+day+"日预计达成";
                        }else {
                            text=newyear+"年"+newmonth+"月"+day+"日预计达成";
                        }
                        predict.setText(text);
                    }
                    predict();

                }else {
                    Toast.makeText(TravelCostActivity.this,"实现时间不能超过出行时间",Toast.LENGTH_LONG).show();
                }
            }
        });

        week.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                week.setBackgroundResource(R.drawable.shape2);
                month.setBackgroundResource(R.drawable.shape);

                W.setTextAppearance(getBaseContext(), R.style.text_style);
                Wmoney.setTextAppearance(getBaseContext(), R.style.text_style);
                predictW.setTextAppearance(getBaseContext(), R.style.text_style);
                M.setTextAppearance(getBaseContext(), R.style.text_style_2);
                Mmoney.setTextAppearance(getBaseContext(), R.style.text_style_2);
                predictM.setTextAppearance(getBaseContext(), R.style.text_style_2);

                click="0";
            }
        });
        month.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                week.setBackgroundResource(R.drawable.shape);
                month.setBackgroundResource(R.drawable.shape2);

                M.setTextAppearance(getBaseContext(), R.style.text_style);
                Mmoney.setTextAppearance(getBaseContext(), R.style.text_style);
                predictM.setTextAppearance(getBaseContext(), R.style.text_style);
                W.setTextAppearance(getBaseContext(), R.style.text_style_2);
                Wmoney.setTextAppearance(getBaseContext(), R.style.text_style_2);
                predictW.setTextAppearance(getBaseContext(), R.style.text_style_2);

                click="1";
            }
        });

    }

    public void Wmt(){
        Wmt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(click.equals("0")){

                    AlertDialog.Builder builder = new AlertDialog.Builder(TravelCostActivity.this);
                    builder.setTitle("选择转入时间");
                    builder.setIcon(getResources().getDrawable(R.drawable.time));
                    final String[] weeks=new String[]
                            {"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
                    builder.setSingleChoiceItems(weeks, -1, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            wmt.setText("每周"+weeks[which]);
                            Toast.makeText(TravelCostActivity.this, "您选择的是：" + weeks[which], Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                            wtime=wmt.getText().toString();

                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();

                }else if(click.equals("1")){
                    AlertDialog.Builder builder = new AlertDialog.Builder(TravelCostActivity.this);
                    builder.setTitle("选择转入时间");
                    builder.setIcon(getResources().getDrawable(R.drawable.time));
                    final String[] days=new String[31];
                    for(int i=0;i<days.length;i++){
                        days[i]= String.valueOf(i+1);
                    }
                    builder.setSingleChoiceItems(days, -1, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            wmt.setText("每月"+days[which]+"号");
                            Toast.makeText(TravelCostActivity.this, "您选择的是：" + days[which]+"号", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                            mtime=wmt.getText().toString();

                        }
                    });

                    AlertDialog dialog = builder.create();
                    dialog.show();
                }else {
                    Toast.makeText(TravelCostActivity.this, "请先选择实现方式", Toast.LENGTH_LONG).show();

                }

            }
        });
    }

    public void Payway(){
        payway.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用花旗api

            }
        });

        /*OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=edazink&scope=zakgo");
        Request request = new Request.Builder()
                .url("https://sandbox.apihub.citi.com/gcb/api/clientCredentials/oauth2/token/us/gcb")
                .post(body)
                .addHeader("accept", "application/json")
                .addHeader("authorization", "REPLACE_THIS_VALUE")
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .build();

        Response response = client.newCall(request).execute();*/


    }

    public void predict(){
        if(ttime>0&&tcost>0){
            if(tcost%(ttime*4)==0){
                wmoney=tcost/(ttime*4);
                Wmoney.setText(String.valueOf(wmoney)+"元");
                predictW.setText("");
            }else {
                wmoney = new BigDecimal((float)tcost/(ttime*4-1))
                        .setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                predictw=tcost-wmoney*(ttime*4-1);
                Wmoney.setText(String.valueOf(wmoney)+"元");
                predictW.setText("最后一周转入"+predictw);
            }

            if(tcost%ttime==0){
                mmoney=tcost/ttime;
                Mmoney.setText(String.valueOf(mmoney)+"元");
                predictM.setText("");
            }else {
                mmoney = new BigDecimal((float)tcost/(ttime-1))
                        .setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                predictm=tcost-mmoney*(ttime-1);
                Mmoney.setText(String.valueOf(mmoney)+"元");
                predictM.setText("最后一月转入"+predictm);

            }

        }
    }

    public void setTitle(){
        title = findViewById(R.id.title_text);
        title.setText("储蓄目标");
        title_btn_left = findViewById(R.id.title_btn_left);
        title_btn_right=findViewById(R.id.title_btn_right);
        title_btn_left.setText("");
        title_btn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
}
